package Offer.offer2019;

import domain.ListNode;

import java.util.Stack;

/**
 * 从尾到头打印链表
 * @author: leiwenkang02@meituan.com
 * @date: 2019/4/16
 * @time: 21:12
 */
public class Offer05 {
    /**
     * 基于栈
     * @param head
     */
    public void printListNodeReversely(ListNode head) {
        Stack<Integer> stack = new Stack<>();
        //1.将元素放入栈中
        ListNode p = head;
        while (p != null) {
            stack.add(p.val);
            p = p.next;
        }

        //2.打印栈内元素
        while (!stack.isEmpty()) {
            System.out.println(stack.pop());
        }
    }

    /**
     * 基于递归
     * @param head
     */
    public void printListNodeReversely2(ListNode head) {
        if (head == null) {
            return;
        }

        printListNodeReversely2(head.next);
        System.out.println(head.val);
    }
}
